import requests
from bs4 import BeautifulSoup

headers = {
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 QuarkPC/4.3.2.475",
    "sec-ch-ua-platform": "macOS",
    "referer": "https://ibaotu.com/",
    "origin": "https://ibaotu.com",
    "accept-language": "zh-CN,zh;q=0.9",
    "accept-encoding": "gzip, deflate, br, zstd",
    "accept": "application/json, text/javascript, */*; q=0.01",
}


def get_audio(url):
    """
    获取音频：包括音频链接信息和标签信息
    this method is used to get the url and the title of the resource what in the gaven url website
    :param url:the gaven website's url
    :return:the resources in the gaven url，
    """
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')
        audio_urls = __get_audio_url(soup)
        audio_names = __get_audio_title(soup)
        audio_tags = __get_audio_tags(soup)
        if not audio_urls or not audio_names or not audio_tags:
            raise Exception("资源信息获取失败")
        return list(zip(audio_names, audio_urls)), audio_tags
    else:
        raise Exception("网络连接失败")


def __audio_url_protocol_checker(audio):
    """
    check the protocol of the url what the gaven resource
    :param resource:the gaven resource
    :return:the resource what after checked
    """
    if not audio['src'].startswith('https:'):
        audio['src'] = 'https:' + audio['src']
    return audio['src']


def __get_audio_url(soup):
    """
    filter the resource that non src attr
    获取音频链接
    :param soup:
    :return:
    """
    audios_url = soup.find_all('audio', recursive=True)
    filtered_audios_url = filter(lambda audio_url: 'src' in audio_url.attrs, audios_url)
    processed_audios_url = map(__audio_url_protocol_checker, filtered_audios_url)
    return list(processed_audios_url)


def __get_audio_title(soup):
    """
    获取音频标题
    :param soup:
    :return:
    """
    audios_title = soup.find_all('li', {'class': 'sc-home-music'}, recursive=True)
    filtered_audios_titles = filter(lambda audio_title: 'pr-data-title' in audio_title.attrs, audios_title)
    processed_audios_titles = map(lambda audio: audio['pr-data-title'], filtered_audios_titles)
    return list(processed_audios_titles)


def __get_audio_tags(soup):
    """
    获取音频标签
    :param soup:
    :return:
    """
    audios_tags = soup.find_all('a', {'class': ['classifys active']})
    processed_audios_tags = map(lambda audio_tag: audio_tag.get_text(), audios_tags)
    return list(processed_audios_tags)